const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = cloud.database().command;

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const user = await db.collection("user").where({
    openid: wxContext.OPENID,
  }).get()

  if (user.data.length == 0) {
    return {
      code: 401,
      data: {},
      msg: "have not login"
    }
  }

  if (user.data[0].status != 0) {
    return {
      code: 401,
      data: {},
      msg: "no privilege"
    }
  }

  let k = new Date()
  let gt = k.valueOf()
  let task = []
  //lt是前一天的当前时间
  let lt = k - 86400000
  task.push(db.collection("timeTable").where({
    timestamp: _.lt(lt)
  }).remove())


  const res = await db.collection("timeTable").where({
    timestamp: _.gt(gt)
  }).orderBy("timestamp", "desc").limit(1).get()

  let list = []
  //当天的六点
  let start = k.setHours(6, 0, 0, 0).valueOf() + 57600000
  //三十天以后的六点
  let end = start + 2592000000


  //如果存在今天以后的时间戳
  if (res.data.length != 0) {
    start = res.data[0].timestamp
    let g = new Date(start).getHours() + 8//加8修正
    if (g != 18) {
      while (g < 18) {
        //6，9，12，15，18
        g += 3
        start += 10800000
        if (start >= end) {
          break
        }
        list.push({
          isOpen: true,
          timestamp: start,
          number: 0,
          message: ""
        })
      }
    }
    //第二天六点
    start+=43200000
  }



  for (let i = 1; i < 150 && start < end; i++) {
    list.push({
      isOpen: true,
      timestamp: start,
      number: 0,
      message: ""
    })
    if (i % 5 == 0) {
      start += 43200000
    }
    else {
      start += 10800000
    }
  }

  if (list.length != 0) {
    task.push(db.collection("timeTable").add({
      data: list
    }))
  }

  const result = await Promise.all(task)

  if (list.length == 0) {
    result.push({
      errMsg: "collection.add:no need"
    })
  }

  return {
    code: 200,
    data: result,
    msg: "success"
  }
};
